package com.ssy.lingxi.pay.serviceimpl.allInPay;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ssy.lingxi.common.constant.Constants;
import com.ssy.lingxi.common.constant.member.MemberTypeEnum;
import com.ssy.lingxi.common.exception.BusinessException;
import com.ssy.lingxi.common.model.dto.UserLoginCacheDTO;
import com.ssy.lingxi.common.response.ResponseCode;
import com.ssy.lingxi.common.response.Wrapper;
import com.ssy.lingxi.component.redis.service.IRedisStringUtils;
import com.ssy.lingxi.pay.api.common.EAccountStatusEnum;
import com.ssy.lingxi.pay.api.common.allInPay.*;
import com.ssy.lingxi.pay.api.model.vo.request.allInPay.*;
import com.ssy.lingxi.pay.api.model.vo.request.allInPay.dto.QueryInExpDetailDTO;
import com.ssy.lingxi.pay.api.model.vo.response.allInPay.*;
import com.ssy.lingxi.pay.config.PayGateWayConfig;
import com.ssy.lingxi.pay.entity.allInPay.AllInPay;
import com.ssy.lingxi.pay.entity.allInPay.AllInPayAttach;
import com.ssy.lingxi.pay.entity.allInPay.AllInPayBank;
import com.ssy.lingxi.pay.model.allInPayModel.MemberServiceUtil;
import com.ssy.lingxi.pay.model.allInPayModel.OrderServiceUtil;
import com.ssy.lingxi.pay.model.allInPayModel.YunClient;
import com.ssy.lingxi.pay.model.assetAccount.AllInPayAttachInfo;
import com.ssy.lingxi.pay.model.vo.request.GateWayPayVO;
import com.ssy.lingxi.pay.model.vo.request.ResendPaySMSVO;
import com.ssy.lingxi.pay.model.vo.request.UserInfoReqVO;
import com.ssy.lingxi.pay.model.vo.response.ResendPaySMSRespVO;
import com.ssy.lingxi.pay.model.vo.response.UserAuthInfoVO;
import com.ssy.lingxi.pay.repository.allInPay.AllInPayAttachRepository;
import com.ssy.lingxi.pay.repository.allInPay.AllInPayBankRepository;
import com.ssy.lingxi.pay.repository.allInPay.AllInPayRepository;
import com.ssy.lingxi.pay.service.IPayCacheService;
import com.ssy.lingxi.pay.service.allInPay.IAllInPayService;
import com.ssy.lingxi.pay.utils.RSAUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 通联支付实现类
 *
 * @author lqa
 * @version 2.0.0
 * @date 2021/11/26
 */
@Service
public class AllInPayServiceImpl implements IAllInPayService {

    private final Logger log = LoggerFactory.getLogger(this.getClass());
    private final static String key = "allInPay";

    @Resource
    private AllInPayRepository allInPayRepository;
    @Resource
    private PayGateWayConfig payGateWayConfig;
    @Resource
    private AllInPayAttachRepository allInPayAttachRepository;
    @Resource
    private IPayCacheService payCacheService;
    @Resource
    private AllInPayBankRepository allInPayBankRepository;
    @Resource
    private IRedisStringUtils redisStringUtils;

    /**
     * 通联支付-订单分账退款申请
     *
     * @param vo 请求参数
     * @return 操作结果
     */
    @Override
    public OrderSplitRefundRespVO orderSplitRefund(OrderSplitRefundVO vo) {
        String cacheParams = redisStringUtils.get(key, Constants.REDIS_PAY_INDEX);
        JSONObject cacheResp = JSONObject.parseObject(cacheParams);
        List<OrderRefundVO> orderRefundList = vo.getOrderRefundList();
        JSONArray reqArray = new JSONArray();
        if (!CollectionUtils.isEmpty(orderRefundList)) {
            for (OrderRefundVO orderRefundVO : orderRefundList) {
                JSONObject req = new JSONObject();
                req.put("splitBizOrderNo", orderRefundVO.getSplitBizOrderNo());
                req.put("amount", new BigDecimal(String.valueOf(orderRefundVO.getAmount())).multiply(new BigDecimal(100)));//元转分
                req.put("bizUserId", orderRefundVO.getBizUserId());
                req.put("totalSplitAmount", new BigDecimal(String.valueOf(orderRefundVO.getTotalSplitAmount())).multiply(new BigDecimal(100)));
                req.put("totalSplitFeeAmount", orderRefundVO.getTotalSplitFeeAmount().longValue());
                List<SplitRefundVO> splitRefundList = orderRefundVO.getSplitRefundList();
                JSONArray refundVOArray = new JSONArray();
                if (!CollectionUtils.isEmpty(splitRefundList)) {
                    for (SplitRefundVO refundVO : splitRefundList) {
                        JSONObject jsonObject = new JSONObject();
                        jsonObject.put("bizUserId", refundVO.getMemberId() + "__" + refundVO.getMemberRoleId());
                        jsonObject.put("accountSetNo", cacheResp.getString("43"));//从缓存中获取平台标准账户集
                        jsonObject.put("amount", new BigDecimal(String.valueOf(refundVO.getAmount())).multiply(new BigDecimal(100)));
                        jsonObject.put("feeAmount", refundVO.getFeeAmount().longValue());
                        jsonObject.put("remark", refundVO.getRemark());
                        refundVOArray.add(jsonObject);
                    }
                }
                req.put("splitRefundList", refundVOArray);
                reqArray.add(req);
            }
        }
        JSONObject resp;
        try {
            String backUrl = payGateWayConfig.getNotifyUrl() + YunClient.backUrl + "/orderSplitRefund";//订单分账退款申请 统一回调地址
            String url = payGateWayConfig.getTestInterfaceUrl();//接口访问地址
            String result = OrderServiceUtil.orderSplitRefund(vo.getBizOrderNo(), vo.getOriBizOrderNo(), vo.getMemberId() + "__" + vo.getMemberRoleId(), vo.getRefundType(), reqArray, backUrl, cacheParams, url);
            resp = JSON.parseObject(result);
            String status = resp.getString("status");
            if (AllInPayResultEnum.SUCCESS.getMsg().equals(status)) {
                JSONObject signedValue = resp.getJSONObject("signedValue");
                OrderSplitRefundRespVO orderSplitRefundRespVO = new OrderSplitRefundRespVO();
                orderSplitRefundRespVO.setBizOrderNo(signedValue.getString("bizOrderNo"));
                orderSplitRefundRespVO.setOrderNo(signedValue.getString("orderNo"));
                orderSplitRefundRespVO.setPayStatus(signedValue.getString("payStatus"));
                orderSplitRefundRespVO.setAmount(signedValue.getString("amount"));
                orderSplitRefundRespVO.setExtendInfo(signedValue.getString("extendInfo"));
                return orderSplitRefundRespVO;
            } else {
                throw new BusinessException(Integer.parseInt(resp.getString("errorCode")), resp.getString("message"));
            }

        } catch (Exception e) {
            throw new BusinessException(ResponseCode.ALL_IN_PAY_ERROR);
        }
    }

    /**
     * 获取通联会员手机号码
     *
     * @param userInfoReqVO 会员信息
     * @return 手机号码
     */
    @Override
    public String getUserPhone(UserInfoReqVO userInfoReqVO) {
        String bizUserId = userInfoReqVO.getMemberId() + "__" + userInfoReqVO.getMemberRoleId();
        AllInPay allInPay = allInPayRepository.findByBizUserId(bizUserId);
        return allInPay != null ? allInPay.getPhone() : "";
    }

    /**
     * 通联支付-确认支付(后台+短信验证码确认)-重发支付短信验证码
     * 收银宝网关支付时需要用到
     *
     * @return 操作结果
     */
    @Override
    public ResendPaySMSRespVO reSendPaySMS(ResendPaySMSVO resendPaySMSVO) {
        String cacheParams = redisStringUtils.get(key, Constants.REDIS_PAY_INDEX);
        JSONObject resp;
        try {
            String url = payGateWayConfig.getTestInterfaceUrl();//接口访问地址
            String result = OrderServiceUtil.resendPaySMS(resendPaySMSVO.getBizOrderNo(), cacheParams, url);
            resp = JSON.parseObject(result);
            String status = resp.getString("status");
            if (AllInPayResultEnum.SUCCESS.getMsg().equals(status)) {
                JSONObject signedValue = resp.getJSONObject("signedValue");
                ResendPaySMSRespVO vo = new ResendPaySMSRespVO();
                vo.setBizOrderNo(signedValue.getString("bizOrderNo"));
                vo.setOrderNo(signedValue.getString("orderNo"));
                vo.setPhone(signedValue.getString("phone"));
                return vo;
            } else {
                throw new BusinessException(Integer.parseInt(resp.getString("errorCode")), resp.getString("message"));
            }

        } catch (Exception e) {
            throw new BusinessException(ResponseCode.ALL_IN_PAY_ERROR);
        }
    }

    /**
     * 确认支付（前台+短信验证码确认）
     * 收银宝网关支付时需要用到
     *
     * @return 跳转链接
     */
    @Override
    public String gateWayPay(Long memberId, Long memberRoleId, GateWayPayVO gateWayPayVO) {
        String cacheParams = redisStringUtils.get(key, Constants.REDIS_PAY_INDEX);
        String bizUserId = memberId + "__" + memberRoleId;
        try {
            String gateWay = YunClient.testGatewayURL;
            return OrderServiceUtil.gateWayPay(bizUserId, gateWayPayVO.getBizOrderNo(), gateWayPayVO.getVerificationCode(), gateWayPayVO.getConsumerIp(), cacheParams, gateWay);
        } catch (Exception e) {
            throw new BusinessException(ResponseCode.ALL_IN_PAY_ERROR);
        }
    }

    /**
     * 查询个人会员是否实名验证或,企业会员是否完成企业审核
     *
     * @param userInfoReqVO 用户信息
     * @return 操作结果
     */
    @Override
    public UserAuthInfoVO getUserInfo(UserInfoReqVO userInfoReqVO) {
        String bizUserId = userInfoReqVO.getMemberId() + "__" + userInfoReqVO.getMemberRoleId();
        UserAuthInfoVO vo = new UserAuthInfoVO();

        AllInPay allInPay = allInPayRepository.findByBizUserId(bizUserId);
        if (!Objects.isNull(allInPay)) {
            vo.setMemberType(allInPay.getAllInMemberType());
            if (allInPay.getMemberType() == AllInPayMemberTypeEnum.ENTERPRISE.getCode().intValue()) {
                vo.setStatus(allInPay.getAccountStatus());
            } else {
                vo.setIsIdentityChecked(allInPay.getIsAuth());
            }
            return vo;
        }
        return vo;
    }

    /**
     * 对公银行列表
     *
     * @return 操作结果
     */
    @Override
    public List<AllInPayBank> getBankList() {
        return allInPayBankRepository.findAll();
    }

    /**
     * 通联支付-平台转账
     *
     * @param vo 请求参数
     * @return 操作结果
     */
    @Override
    public ApplicationTransferRespVO applicationTransfer(ApplicationTransferVO vo) {
        String cacheParams = redisStringUtils.get(key, Constants.REDIS_PAY_INDEX);
        JSONObject cacheResp = JSONObject.parseObject(cacheParams);
        vo.setSourceAccountSetNo(cacheResp.getString("43"));
        vo.setTargetAccountSetNo(cacheResp.getString("44"));
        String bizUserId = vo.getMemberId() + "__" + vo.getMemberRoleId();
        JSONObject resp;
        try {
            String url = payGateWayConfig.getTestInterfaceUrl();//接口访问地址
            String result = OrderServiceUtil.applicationTransfer(vo.getBizTransferNo(), vo.getSourceAccountSetNo(), bizUserId, vo.getTargetAccountSetNo(),
                    new BigDecimal(String.valueOf(vo.getAmount())).multiply(new BigDecimal("100")).longValue(), vo.getExtendInfo(), cacheParams, url);
            resp = JSON.parseObject(result);
        } catch (Exception e) {
            throw new BusinessException(ResponseCode.ALL_IN_PAY_ERROR);
        }
        String status = resp.getString("status");
        if (AllInPayResultEnum.SUCCESS.getMsg().equals(status)) {
            JSONObject signedValue = resp.getJSONObject("signedValue");
            ApplicationTransferRespVO respVO = new ApplicationTransferRespVO();
            respVO.setTransferNo(signedValue.getString("transferNo"));
            respVO.setBizTransferNo(signedValue.getString("bizTransferNo"));
            respVO.setAmount(new BigDecimal(signedValue.getString("amount")).multiply(new BigDecimal("0.01")).doubleValue());
            respVO.setExtendInfo(signedValue.getString("extendInfo"));
            return respVO;
        } else {
            throw new BusinessException(Integer.parseInt(resp.getString("errorCode")), resp.getString("message"));
        }

    }

    /**
     * 通联支付-退款申请
     *
     * @param vo 请求对象
     * @return 操作结果
     */
    @Override
    public RefundRespVO refund(RefundVO vo) {
        String cacheParams = redisStringUtils.get(key, Constants.REDIS_PAY_INDEX);
        String bizUserId = vo.getMemberId() + "__" + vo.getMemberRoleId();
        JSONObject resp;
        try {
            String backUrl = payGateWayConfig.getNotifyUrl() + YunClient.backUrl + "/refund";//退款申请 统一回调地址
            String url = payGateWayConfig.getTestInterfaceUrl();//接口访问地址
            String result = OrderServiceUtil.refund(vo.getBizOrderNo(), vo.getOriBizOrderNo(), bizUserId, vo.getRefundType(), vo.getRefundList(), backUrl, new BigDecimal(String.valueOf(vo.getAmount())).multiply(new BigDecimal("100")).longValue(), vo.getCouponAmount(), vo.getFeeAmount(), vo.getExtendInfo(), cacheParams, url);
            resp = JSON.parseObject(result);
        } catch (Exception e) {
            throw new BusinessException(ResponseCode.ALL_IN_PAY_ERROR);
        }
        String status = resp.getString("status");
        if (AllInPayResultEnum.SUCCESS.getMsg().equals(status)) {
            JSONObject signedValue = resp.getJSONObject("signedValue");
            RefundRespVO respVO = new RefundRespVO();
            respVO.setPayStatus(signedValue.getString("payStatus"));
            respVO.setPayFailMessage(signedValue.getString("payFailMessage"));
            respVO.setBizOrderNo(signedValue.getString("bizOrderNo"));
            respVO.setOrderNo(signedValue.getString("orderNo"));
            respVO.setAmount(new BigDecimal(signedValue.getString("amount")).multiply(new BigDecimal("0.01")).doubleValue());
            respVO.setCouponAmount(new BigDecimal(signedValue.getString("couponAmount")).multiply(new BigDecimal("0.01")).doubleValue());
            respVO.setFeeAmount(new BigDecimal(signedValue.getString("feeAmount")).multiply(new BigDecimal("0.01")).doubleValue());
            respVO.setExtendInfo(signedValue.getString("extendInfo"));
            return respVO;
        } else {
            throw new BusinessException(Integer.parseInt(resp.getString("errorCode")), resp.getString("message"));
        }

    }

    /**
     * 通联支付-批量托管代付（标准版）(付款到账户余额)
     *
     * @param vo 请求对象
     * @return 成功时返回商户订单号
     */
    @Override
    public String batchAgentPay(BatchAgentPayVO vo) {
        String cacheParams = redisStringUtils.get(key, Constants.REDIS_PAY_INDEX);
        JSONObject resp;
        try {
            String backUrl = payGateWayConfig.getNotifyUrl() + YunClient.backUrl + "/batchAgentPay";//批量托管代付 统一回调地址
            String url = payGateWayConfig.getTestInterfaceUrl();//接口访问地址
            String result = OrderServiceUtil.batchAgentPay(vo.getBizBatchNo(), vo.getBatchPayList(), vo.getTradeCode(), backUrl,cacheParams,url);
            resp = JSON.parseObject(result);
        } catch (Exception e) {
            throw new BusinessException(ResponseCode.ALL_IN_PAY_ERROR);
        }
        String status = resp.getString("status");
        if (AllInPayResultEnum.SUCCESS.getMsg().equals(status)) {
            JSONObject signedValue = resp.getJSONObject("signedValue");
            return signedValue.getString("bizBatchNo");
        } else {
            throw new BusinessException(Integer.parseInt(resp.getString("errorCode")), resp.getString("message"));
        }

    }

    /**
     * 通联支付-单笔托管代付（标准版）
     *
     * @param vo 请求对象
     * @return 操作结果
     */
    @Override
    public SignalAgentPayRespVO signalAgentPay(SignalAgentPayVO vo) {
        String cacheParams = redisStringUtils.get(key, Constants.REDIS_PAY_INDEX);
        Long memberId = vo.getMemberId();
        Long roleId = vo.getMemberRoleId();
        JSONObject cacheValue = JSONObject.parseObject(cacheParams);
        if (memberId != 1 && roleId != 1) {
            vo.setAccountSetNo(cacheValue.getString("44"));
        } else {
            vo.setAccountSetNo(cacheValue.getString("43"));
        }
        JSONArray collectPayList = new JSONArray();
        if (!CollectionUtils.isEmpty(vo.getCollectPayList())) {
            for (CollectPayVO collectPayVO : vo.getCollectPayList()) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("bizOrderNo", collectPayVO.getBizOrderNo());
                jsonObject.put("amount", new BigDecimal(String.valueOf(collectPayVO.getAmount())).multiply(new BigDecimal("100")).longValue());
                collectPayList.add(jsonObject);
            }
        }
        JSONObject resp;
        try {

            String backUrl = payGateWayConfig.getNotifyUrl() + YunClient.backUrl + "/signalAgentPay";
            String url = payGateWayConfig.getTestInterfaceUrl();//接口访问地址
            String bizUserId = memberId + "__" + roleId;
            String result = OrderServiceUtil.signalAgentPay(vo.getBizOrderNo(), collectPayList, bizUserId, vo.getAccountSetNo(), backUrl,
                    new BigDecimal(String.valueOf(vo.getAmount())).multiply(new BigDecimal("100")).longValue(),
                    new BigDecimal(String.valueOf(vo.getFee())).multiply(new BigDecimal("100")).longValue(), vo.getTradeCode(), cacheParams, url);
            resp = JSON.parseObject(result);
        } catch (Exception e) {
            throw new BusinessException(ResponseCode.ALL_IN_PAY_ERROR);
        }
        String status = resp.getString("status");
        if (AllInPayResultEnum.SUCCESS.getMsg().equals(status)) {
            JSONObject signedValue = resp.getJSONObject("signedValue");
            SignalAgentPayRespVO respVO = new SignalAgentPayRespVO();
            respVO.setPayStatus(signedValue.getString("payStatus"));
            respVO.setPayFailMessage(signedValue.getString("payFailMessage"));
            respVO.setBizOrderNo(signedValue.getString("bizOrderNo"));
            respVO.setOrderNo(signedValue.getString("orderNo"));
            respVO.setPayWhereabouts(signedValue.getLong("payWhereabouts"));
            return respVO;
        } else {
            throw new BusinessException(Integer.parseInt(resp.getString("errorCode")), resp.getString("message"));
        }

    }

    /**
     * 通联支付-托管代收申请（标准版）(支付宝/微信PC端正扫,支付宝app(原生或者收银宝的),微信app(只有原生))
     *
     * @param vo 请求参数
     * @return 操作结果
     */
    @Override
    public ConsumeApplyRespVO scanAgentCollectApply(AgentCollectApplyVO vo) {
        String cacheParams = redisStringUtils.get(key, Constants.REDIS_PAY_INDEX);
        JSONObject cacheValue = JSONObject.parseObject(cacheParams);
        if (vo.getMemberId() != 1 && vo.getMemberRoleId() != 1) {
            vo.setAccountSetNo(cacheValue.getString("44"));
        } else {
            vo.setAccountSetNo(cacheValue.getString("43"));
        }
        //封装通联支付附加数据
        //这样可以简短附加数据的长度
        AllInPayAttachInfo allInPayAttachInfo = new AllInPayAttachInfo();
        // allInPayAttachInfo.setPayType(vo.getPayType());
        // allInPayAttachInfo.setBizUserId(vo.getMemberId() + "__" + vo.getMemberRoleId());
        allInPayAttachInfo.setAttach(vo.getExtendInfo());
        allInPayAttachInfo.setServiceType(vo.getServiceType());
        String attachJson = payCacheService.serializeObject(allInPayAttachInfo);
        JSONObject resp;
        try {
            JSONArray recieverList = new JSONArray();
            if (!CollectionUtils.isEmpty(vo.getRecieverList())) {
                for (RecieverVO recieverVO : vo.getRecieverList()) {
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("bizUserId", recieverVO.getMemberId() + "__" + recieverVO.getMemberRoleId());
                    jsonObject.put("amount", new BigDecimal(String.valueOf(recieverVO.getAmount())).multiply(new BigDecimal("100")).longValue());
                    recieverList.add(jsonObject);
                }
            }
            String bizUserId = vo.getMemberId() + "__" + vo.getMemberRoleId();
            //判断是否进行收银宝快捷支付
            if (AllInPayPayMethodEnum.QUICKPAY_VSP.getPayMethod().equals(vo.getPayMethodStr())) {
                AllInPay allInPay = allInPayRepository.findByBizUserId(bizUserId);
                AllInPayAttach payAttach = allInPayAttachRepository.findByBizUserId(bizUserId);
                if (AllInPayMemberTypeEnum.ENTERPRISE.getCode().equals(allInPay.getAllInMemberType().longValue())) {//企业会员
                    vo.setBankCardNo(payAttach.getAccountNo());
                } else {
                    vo.setBankCardNo(payAttach.getBankNo());
                }
            }
            String backUrl = payGateWayConfig.getNotifyUrl() + YunClient.backUrl + "/agentCollectApply";
            String url = payGateWayConfig.getTestInterfaceUrl();//接口访问地址
            String payerId = vo.getMemberId() + "__" + vo.getMemberRoleId();
            String result = OrderServiceUtil.scanAgentCollectApply(vo.getBizOrderNo(), payerId,
                    new BigDecimal(String.valueOf(vo.getAmount())).multiply(new BigDecimal("100")).longValue(),
                    new BigDecimal(String.valueOf(vo.getFee())).multiply(new BigDecimal("100")).longValue(), vo.getValidateType().longValue(), null,
                    backUrl, vo.getPayMethodStr(), vo.getLimitPay(), vo.getVspCusId(), vo.getSubAppId(), vo.getAcct(),
                    vo.getTradeCode(), vo.getAllInPayType(), vo.getBankCardNo(), vo.getIndustryCode(), vo.getIndustryName(), attachJson, vo.getSource(), recieverList, cacheParams, url, vo.getCusIp());
            resp = JSON.parseObject(result);
        } catch (Exception e) {
            throw new BusinessException(ResponseCode.ALL_IN_PAY_ERROR);
        }
        String status = resp.getString("status");
        if (AllInPayResultEnum.SUCCESS.getMsg().equals(status)) {
            JSONObject signedValue = resp.getJSONObject("signedValue");
            ConsumeApplyRespVO respVO = new ConsumeApplyRespVO();
            respVO.setPayStatus(signedValue.getString("payStatus"));
            respVO.setPayFailMessage(signedValue.getString("payFailMessage"));
            respVO.setBizUserId(signedValue.getString("bizUserId"));
            respVO.setBizOrderNo(signedValue.getString("bizOrderNo"));
            respVO.setTradeNo(signedValue.getString("tradeNo"));
            respVO.setExtendInfo(signedValue.getString("extendInfo"));
            respVO.setPayInfo(signedValue.getString("payInfo"));
            respVO.setWeChatAPPInfo(signedValue.getString("weChatAPPInfo"));
            return respVO;
        } else {
            throw new BusinessException(Integer.parseInt(resp.getString("errorCode")), resp.getString("message"));
        }

    }

    /**
     * 通联支付-托管代收申请（标准版）(余额支付方式)
     *
     * @param vo 请求参数
     * @return 操作结果
     */
    @Override
    public ConsumeApplyRespVO balanceAgentCollectApply(AgentCollectApplyVO vo) {
        String cacheParams = redisStringUtils.get(key, Constants.REDIS_PAY_INDEX);
        JSONObject cacheValue = JSONObject.parseObject(cacheParams);
        if (vo.getMemberId() != 1 && vo.getMemberRoleId() != 1) {
            vo.setAccountSetNo(cacheValue.getString("44"));
        } else {
            vo.setAccountSetNo(cacheValue.getString("43"));
        }
        //封装通联支付附加数据
        //这样可以简短附加数据的长度
        AllInPayAttachInfo allInPayAttachInfo = new AllInPayAttachInfo();
        // allInPayAttachInfo.setPayType(vo.getPayType());
        // allInPayAttachInfo.setBizUserId(vo.getMemberId() + "__" + vo.getMemberRoleId());
        allInPayAttachInfo.setAttach(vo.getExtendInfo());
        allInPayAttachInfo.setServiceType(vo.getServiceType());
        String attachJson = payCacheService.serializeObject(allInPayAttachInfo);
        JSONObject resp;
        try {
            JSONArray jsonArray = new JSONArray();
            if (!CollectionUtils.isEmpty(vo.getRecieverList())) {
                for (RecieverVO recieverVO : vo.getRecieverList()) {
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("bizUserId", recieverVO.getMemberId() + "__" + recieverVO.getMemberRoleId());
                    // jsonObject.put("bizUserId", 236 + "__" + 3);
                    jsonObject.put("amount", new BigDecimal(String.valueOf(recieverVO.getAmount())).multiply(new BigDecimal("100")).longValue());
                    jsonArray.add(jsonObject);
                }
            }
            String backUrl = payGateWayConfig.getNotifyUrl() + YunClient.backUrl + "/agentCollectApply";
            String url = payGateWayConfig.getTestInterfaceUrl();//接口访问地址
            String payerId = vo.getMemberId() + "__" + vo.getMemberRoleId();
            String result = OrderServiceUtil.balanceAgentCollectApply(vo.getBizOrderNo(), payerId,
                    new BigDecimal(String.valueOf(vo.getAmount())).multiply(new BigDecimal("100")).longValue(),
                    new BigDecimal(String.valueOf(vo.getFee())).multiply(new BigDecimal("100")).longValue(),
                    vo.getValidateType().longValue(), null, backUrl, vo.getPayMethodStr(), vo.getAccountSetNo(), vo.getTradeCode(),
                    vo.getIndustryCode(), vo.getIndustryName(), attachJson, vo.getSource(), jsonArray, cacheParams, url);
            resp = JSON.parseObject(result);
        } catch (Exception e) {
            throw new BusinessException(ResponseCode.ALL_IN_PAY_ERROR);
        }
        String status = resp.getString("status");
        if (AllInPayResultEnum.SUCCESS.getMsg().equals(status)) {
            JSONObject signedValue = resp.getJSONObject("signedValue");
            ConsumeApplyRespVO respVO = new ConsumeApplyRespVO();
            respVO.setPayStatus(signedValue.getString("payStatus"));
            respVO.setPayFailMessage(signedValue.getString("payFailMessage"));
            respVO.setBizUserId(signedValue.getString("bizUserId"));
            respVO.setBizOrderNo(signedValue.getString("bizOrderNo"));
            respVO.setTradeNo(signedValue.getString("tradeNo"));
            respVO.setExtendInfo(signedValue.getString("extendInfo"));
            return respVO;
        } else {
            throw new BusinessException(Integer.parseInt(resp.getString("errorCode")), resp.getString("message"));
        }

    }

    /**
     * 通联支付-消费申请(支付宝/微信PC端正扫,支付宝app(原生或者收银宝的),微信app(只有原生))
     *
     * @param vo 请求参数
     * @return 操作结果
     */
    @Override
    public ConsumeApplyRespVO scanBalanceConsumeApply(ConsumeApplyVO vo) {
        String payerId = vo.getMemberId() + "__" + vo.getMemberRoleId();
        String recieverId = vo.getRecieverMemberId() + "__" + vo.getRecieverMemberRoleId();
        recieverId = !"1__1".equals(recieverId) ? recieverId : "#yunBizUserId_B2C#";//判断是不是转给平台
        String cacheParams = redisStringUtils.get(key, Constants.REDIS_PAY_INDEX);
        JSONObject cacheValue = JSONObject.parseObject(cacheParams);
        if (vo.getMemberId() != 1 && vo.getMemberRoleId() != 1) {
            vo.setAccountSetNo(cacheValue.getString("44"));
        } else {
            vo.setAccountSetNo(cacheValue.getString("43"));
        }
        String bizUserId = vo.getMemberId() + "__" + vo.getMemberRoleId();
        //封装通联支付附加数据 长度最多为50
        //这样可以简短附加数据的长度
        AllInPayAttachInfo allInPayAttachInfo = new AllInPayAttachInfo();
        allInPayAttachInfo.setAttach(vo.getExtendInfo());
        allInPayAttachInfo.setServiceType(vo.getServiceType());
        String attachJson = payCacheService.serializeObject(allInPayAttachInfo);
        // String attachJson = "";//payCacheService.serializeObject(allInPayAttachInfo);
        JSONObject resp;
        try {
            String backUrl = payGateWayConfig.getNotifyUrl() + YunClient.backUrl + "/consumeApply";
            //判断是否进行收银宝快捷支付
            if (AllInPayPayMethodEnum.QUICKPAY_VSP.getPayMethod().equals(vo.getPayMethodStr())) {
                AllInPay allInPay = allInPayRepository.findByBizUserId(bizUserId);
                AllInPayAttach payAttach = allInPayAttachRepository.findByBizUserId(bizUserId);
                if (AllInPayMemberTypeEnum.ENTERPRISE.getCode().equals(allInPay.getAllInMemberType().longValue())) {//企业会员
                    vo.setBankCardNo(payAttach.getAccountNo());
                } else {
                    vo.setBankCardNo(payAttach.getBankNo());
                }
            }
            String url = payGateWayConfig.getTestInterfaceUrl();//接口访问地址
            String result = OrderServiceUtil.scanBalanceConsumeApply(payerId, recieverId, vo.getBizOrderNo(),
                    new BigDecimal(String.valueOf(vo.getAmount())).multiply(new BigDecimal("100")).longValue(),
                    new BigDecimal(String.valueOf(vo.getFee())).multiply(new BigDecimal("100")).longValue(), vo.getValidateType(), "test",
                    backUrl, vo.getPayMethodStr(), vo.getLimitPay(), vo.getVspCusId(), vo.getSubAppId(), vo.getAcct(), vo.getAllInPayType(),
                    vo.getBankCardNo(), vo.getIndustryCode(), vo.getIndustryName(), attachJson, cacheParams, url, vo.getCusIp());
            resp = JSON.parseObject(result);
        } catch (Exception e) {
            throw new BusinessException(ResponseCode.ALL_IN_PAY_ERROR);
        }
        String status = resp.getString("status");
        if (AllInPayResultEnum.SUCCESS.getMsg().equals(status)) {
            JSONObject signedValue = resp.getJSONObject("signedValue");
            ConsumeApplyRespVO respVO = new ConsumeApplyRespVO();
            respVO.setPayStatus(signedValue.getString("payStatus"));
            respVO.setPayFailMessage(signedValue.getString("payFailMessage"));
            respVO.setBizUserId(signedValue.getString("bizUserId"));
            respVO.setBizOrderNo(signedValue.getString("bizOrderNo"));
            respVO.setTradeNo(signedValue.getString("tradeNo"));
            respVO.setExtendInfo(signedValue.getString("extendInfo"));
            respVO.setPayInfo(signedValue.getString("payInfo"));
            respVO.setWeChatAPPInfo(signedValue.getString("weChatAPPInfo"));
            return respVO;
        } else {
            throw new BusinessException(Integer.parseInt(resp.getString("errorCode")), resp.getString("message"));
        }

    }

    /**
     * 通联支付-消费申请(余额支付方式)
     *
     * @param vo 请求参数
     * @return 操作结果
     */
    @Override
    public ConsumeApplyRespVO balanceConsumeApply(ConsumeApplyVO vo) {
        String payerId = vo.getMemberId() + "__" + vo.getMemberRoleId();
        String recieverId = vo.getRecieverMemberId() + "__" + vo.getRecieverMemberRoleId();
        recieverId = !"1__1".equals(recieverId) ? recieverId : "#yunBizUserId_B2C#";//判断是不是转给平台
        String cacheParams = redisStringUtils.get(key, Constants.REDIS_PAY_INDEX);
        JSONObject cacheValue = JSONObject.parseObject(cacheParams);
        if (vo.getMemberId() != 1 && vo.getMemberRoleId() != 1) {
            vo.setAccountSetNo(cacheValue.getString("44"));
        } else {
            vo.setAccountSetNo(cacheValue.getString("43"));

        }

        //封装通联支付附加数据
        //这样可以简短附加数据的长度
        AllInPayAttachInfo allInPayAttachInfo = new AllInPayAttachInfo();
        // allInPayAttachInfo.setPayType(vo.getPayType());
        // allInPayAttachInfo.setBizUserId(vo.getMemberId() + "__" + vo.getMemberRoleId());
        allInPayAttachInfo.setAttach(vo.getExtendInfo());
        allInPayAttachInfo.setServiceType(vo.getServiceType());
        String attachJson = payCacheService.serializeObject(allInPayAttachInfo);
        JSONObject resp;
        try {
            String backUrl = payGateWayConfig.getNotifyUrl() + YunClient.backUrl + "/consumeApply";
            String url = payGateWayConfig.getTestInterfaceUrl();//接口访问地址
            String result = OrderServiceUtil.balanceConsumeApply(payerId, recieverId, vo.getBizOrderNo(),
                    new BigDecimal(String.valueOf(vo.getAmount())).multiply(new BigDecimal("100")).longValue(),
                    new BigDecimal(String.valueOf(vo.getFee())).multiply(new BigDecimal("100")).longValue(),
                    vo.getValidateType(), null, backUrl, vo.getPayMethodStr(), vo.getAccountSetNo(), vo.getIndustryCode(), vo.getIndustryName(), attachJson, cacheParams, url);
            resp = JSON.parseObject(result);
        } catch (Exception e) {
            throw new BusinessException(ResponseCode.ALL_IN_PAY_ERROR);
        }
        String status = resp.getString("status");
        if (AllInPayResultEnum.SUCCESS.getMsg().equals(status)) {
            JSONObject signedValue = resp.getJSONObject("signedValue");
            ConsumeApplyRespVO respVO = new ConsumeApplyRespVO();
            respVO.setPayStatus(signedValue.getString("payStatus"));
            respVO.setPayFailMessage(signedValue.getString("payFailMessage"));
            respVO.setBizUserId(signedValue.getString("bizUserId"));
            respVO.setBizOrderNo(signedValue.getString("bizOrderNo"));
            respVO.setTradeNo(signedValue.getString("tradeNo"));
            respVO.setExtendInfo(signedValue.getString("extendInfo"));
            return respVO;
        } else {
            throw new BusinessException(Integer.parseInt(resp.getString("errorCode")), resp.getString("message"));
        }


    }

    /**
     * 通联支付-确认支付(后台+短信验证码确认)
     *
     * @param sysUser 当前登录用户
     * @param vo      请求参数
     * @return 操作结果
     */
    @Override
    public PayRespVO pay(UserLoginCacheDTO sysUser, PayVO vo) {
        String cacheParams = redisStringUtils.get(key, Constants.REDIS_PAY_INDEX);
        String bizUserId;
        if (sysUser.getMemberId() == 1 && sysUser.getMemberRoleId() == 1) {//如果是平台
            bizUserId = "#yunBizUserId_B2C#";
        } else {
            bizUserId = sysUser.getMemberId() + "__" + sysUser.getMemberRoleId();
        }

        JSONObject resp;
        try {
            String url = payGateWayConfig.getTestInterfaceUrl();//接口访问地址
            String result = OrderServiceUtil.pay(bizUserId, vo.getBizOrderNo(), null, vo.getVerificationCode(), vo.getConsumerIp(), cacheParams, url);
            resp = JSON.parseObject(result);
        } catch (Exception e) {
            throw new BusinessException(ResponseCode.ALL_IN_PAY_ERROR);
        }
        String status = resp.getString("status");
        if (AllInPayResultEnum.SUCCESS.getMsg().equals(status)) {
            JSONObject signedValue = resp.getJSONObject("signedValue");
            String payStatus = signedValue.getString("payStatus");
            if (EAccountPayStatusEnum.FAIL.getCode().equals(payStatus) || EAccountPayStatusEnum.UNPAY.getCode().equals(payStatus)) {
                throw new BusinessException(signedValue.getString("payFailMessage"));
            } else {
                PayRespVO respVO = new PayRespVO();
                respVO.setPayStatus(payStatus);
                respVO.setPayFailMessage(signedValue.getString("payFailMessage"));
                respVO.setBizUserId(signedValue.getString("bizUserId"));
                respVO.setBizOrderNo(signedValue.getString("bizOrderNo"));
                return respVO;
            }
        } else {
            throw new BusinessException(Integer.parseInt(resp.getString("errorCode")), resp.getString("message"));
        }

    }

    /**
     * 通联支付-提现申请
     *
     * @param sysUser 当前登录用户
     * @param vo      请求参数
     * @return 操作结果
     */
    @Override
    public WithdrawApplyRespVO withdrawApply(UserLoginCacheDTO sysUser, WithdrawApplyVO vo) {
        String cacheParams = redisStringUtils.get(key, Constants.REDIS_PAY_INDEX);
        JSONObject cacheValue = JSONObject.parseObject(cacheParams);
        if (sysUser.getMemberId() != 1 && sysUser.getMemberRoleId() != 1) {
            vo.setAccountSetNo(cacheValue.getString("44"));
        } else {
            vo.setAccountSetNo(cacheValue.getString("43"));
        }
        String bizUserId = sysUser.getMemberId() + "__" + sysUser.getMemberRoleId();
        JSONObject resp;
        try {
            String backUrl = payGateWayConfig.getNotifyUrl() + YunClient.backUrl + "/withdrawApply";
            String url = payGateWayConfig.getTestInterfaceUrl();//接口访问地址
            String result = OrderServiceUtil.withdrawApply(bizUserId, vo.getBizOrderNo(), vo.getAccountSetNo(), vo.getAmount().multiply(new BigDecimal("100")).longValue(), vo.getPayMethodStr(), vo.getBankCardNo(), vo.getBankCardPro().longValue(), null, null, null, null, vo.getWithdrawType(), backUrl, cacheParams, url);
            resp = JSON.parseObject(result);
        } catch (Exception e) {
            throw new BusinessException(ResponseCode.ALL_IN_PAY_ERROR);
        }
        String status = resp.getString("status");
        if (AllInPayResultEnum.SUCCESS.getMsg().equals(status)) {
            JSONObject signedValue = resp.getJSONObject("signedValue");
            WithdrawApplyRespVO respVO = new WithdrawApplyRespVO();
            respVO.setPayStatus(signedValue.getString("payStatus"));
            respVO.setPayFailMessage(signedValue.getString("payFailMessage"));
            respVO.setBizUserId(signedValue.getString("bizUserId"));
            respVO.setOrderNo(signedValue.getString("orderNo"));
            respVO.setBizOrderNo(signedValue.getString("bizOrderNo"));
            return respVO;
        } else {
            throw new BusinessException(Integer.parseInt(resp.getString("errorCode")), resp.getString("message"));
        }
    }

    /**
     * 通联支付-充值申请
     *
     * @param sysUser 当前登录用户
     * @param vo      请求参数
     * @return 操作结果
     */
    @Override
    public DepositApplyRespVO depositApply(UserLoginCacheDTO sysUser, DepositApplyVO vo) {
        String cacheParams = redisStringUtils.get(key, Constants.REDIS_PAY_INDEX);
        JSONObject cacheValue = JSONObject.parseObject(cacheParams);
        if (sysUser.getMemberId() != 1 && sysUser.getMemberRoleId() != 1) {
            vo.setAccountSetNo(cacheValue.getString("44"));
        } else {
            vo.setAccountSetNo(cacheValue.getString("43"));
        }
        String bizUserId = sysUser.getMemberId() + "__" + sysUser.getMemberRoleId();
        JSONObject resp;
        String bankCardNo = null;
        try {
            //判断是否进行收银宝快捷支付
            if (AllInPayPayMethodEnum.QUICKPAY_VSP.getPayMethod().equals(vo.getPayMethodStr())) {
                AllInPay allInPay = allInPayRepository.findByBizUserId(bizUserId);
                AllInPayAttach payAttach = allInPayAttachRepository.findByBizUserId(bizUserId);
                if (AllInPayMemberTypeEnum.ENTERPRISE.getCode().equals(allInPay.getAllInMemberType().longValue())) {//企业会员
                    bankCardNo = payAttach.getAccountNo();
                } else {
                    bankCardNo = payAttach.getBankNo();
                }
            }
            String backUrl = payGateWayConfig.getNotifyUrl() + YunClient.backUrl + "/depositApply";
            String url = payGateWayConfig.getTestInterfaceUrl();//接口访问地址
            String result = OrderServiceUtil.depositApply(bizUserId, vo.getBizOrderNo(), vo.getPayMethodStr(), bankCardNo, "no_credit", vo.getOpenId(), null, vo.getVspCusId(), vo.getSubAppId(), null,
                    null, vo.getAccountSetNo(), "test", backUrl, vo.getAmount().multiply(new BigDecimal("100")).longValue(), cacheParams, url, vo.getCusIp());
            resp = JSON.parseObject(result);
        } catch (Exception e) {
            throw new BusinessException(ResponseCode.ALL_IN_PAY_ERROR);
        }
        String status = resp.getString("status");
        if (AllInPayResultEnum.SUCCESS.getMsg().equals(status)) {
            JSONObject signedValue = resp.getJSONObject("signedValue");
            String payStatus = signedValue.getString("payStatus");
            String payFailMessage = signedValue.getString("payFailMessage");
            if (EAccountPayStatusEnum.FAIL.getCode().equals(payStatus) || EAccountPayStatusEnum.UNPAY.getCode().equals(payStatus)) {
                throw new BusinessException(payFailMessage);
            } else {
                DepositApplyRespVO respVO = new DepositApplyRespVO();
                respVO.setPayStatus(payStatus);
                respVO.setPayFailMessage(payFailMessage);
                respVO.setBizUserId(signedValue.getString("bizUserId"));
                respVO.setOrderNo(signedValue.getString("orderNo"));
                respVO.setBizOrderNo(signedValue.getString("bizOrderNo"));
                respVO.setWeChatAPPInfo(signedValue.getString("weChatAPPInfo"));
                respVO.setPayInfo(signedValue.getString("payInfo"));
                respVO.setValidateType(signedValue.getLong("validateType"));
                return respVO;
            }
        } else {
            throw new BusinessException(Integer.parseInt(resp.getString("errorCode")), resp.getString("message"));
        }
    }

    /**
     * 通联支付-设置或修改或重置支付密码【密码验证版】
     *
     * @param sysUser 当前登录用户
     * @param vo      请求参数
     * @return 操作结果
     */
    @Override
    public Wrapper<String> setPayPwd(UserLoginCacheDTO sysUser, SetPayPwdVO vo) {
        String cacheParams = redisStringUtils.get(key, Constants.REDIS_PAY_INDEX);
        String bizUserId = sysUser.getMemberId() + "__" + sysUser.getMemberRoleId();
        if (vo.getType() == 1) {//1-设置密码
            String backUrl = payGateWayConfig.getNotifyUrl() + YunClient.backUrl + "/setPayPwd";
            try {
                String url = payGateWayConfig.getTestInterfaceUrl();//接口访问地址
                String result = OrderServiceUtil.setPayPwd(bizUserId, vo.getJumpPageType(), vo.getPhone(), vo.getName(), vo.getIdentityType(), vo.getIdentityNo(), backUrl, vo.getType(), cacheParams, url);
                return Wrapper.success(result);
            } catch (Exception e) {
                throw new BusinessException(ResponseCode.ALL_IN_PAY_ERROR);
            }
        }
        if (vo.getType() == 2) {//2-修改密码
            String backUrl = payGateWayConfig.getNotifyUrl() + YunClient.backUrl + "/updatePayPwd";
            try {
                String url = payGateWayConfig.getTestInterfaceUrl();//接口访问地址
                String result = OrderServiceUtil.setPayPwd(bizUserId, vo.getJumpPageType(), vo.getPhone(), vo.getName(), vo.getIdentityType(), vo.getIdentityNo(), backUrl, vo.getType(), cacheParams, url);
                return Wrapper.success(result);
            } catch (Exception e) {
                return Wrapper.fail(ResponseCode.ALL_IN_PAY_ERROR);
            }
        }
        if (vo.getType() == 3) {//2-重置密码
            String backUrl = payGateWayConfig.getNotifyUrl() + YunClient.backUrl + "/resetPayPwd";
            try {
                String url = payGateWayConfig.getTestInterfaceUrl();//接口访问地址
                String result = OrderServiceUtil.setPayPwd(bizUserId, vo.getJumpPageType(), vo.getPhone(), vo.getName(), vo.getIdentityType(), vo.getIdentityNo(), backUrl, vo.getType(), cacheParams, url);
                return Wrapper.success(result);
            } catch (Exception e) {
                return Wrapper.fail(ResponseCode.ALL_IN_PAY_ERROR);
            }
        }
        return Wrapper.success();
    }

    /**
     * 联支付-冻结金额
     *
     * @param memberId         会员id
     * @param memberRoleId     会员角色id
     * @param freezeMoneyReqVO 请求数据
     * @return 冻结结果
     */
    @Override
    public FreezeMoneyRespVO freezeMoney(Long memberId, Long memberRoleId, FreezeMoneyReqVO freezeMoneyReqVO) {
        String cacheParams = redisStringUtils.get(key, Constants.REDIS_PAY_INDEX);
        JSONObject cacheValue = JSONObject.parseObject(cacheParams);
        if (memberId != 1 && memberRoleId != 1) {
            freezeMoneyReqVO.setAccountSetNo(cacheValue.getString("44"));
        } else {
            freezeMoneyReqVO.setAccountSetNo(cacheValue.getString("43"));
        }
        String bizUserId = memberId + "__" + memberRoleId;
        String result;
        JSONObject resp;
        String url = payGateWayConfig.getTestInterfaceUrl();//接口访问地址
        if (freezeMoneyReqVO.getType().equals(EAccountStatusEnum.freeze.getCode())) {//1-冻结 2-解冻

            try {

                result = OrderServiceUtil.freezeMoney(bizUserId, freezeMoneyReqVO.getBizFreeZenNo(), freezeMoneyReqVO.getAccountSetNo(), freezeMoneyReqVO.getAmount().multiply(new BigDecimal(100)).longValue(), cacheParams, url);//元转分
                resp = JSON.parseObject(result);
            } catch (Exception e) {
                throw new BusinessException(ResponseCode.ALL_IN_PAY_ERROR);
            }
            String status = resp.getString("status");
            if (AllInPayResultEnum.SUCCESS.getMsg().equals(status)) {
                FreezeMoneyRespVO vo = new FreezeMoneyRespVO();
                vo.setAmount(new BigDecimal(resp.getJSONObject("signedValue").getLong("amount")).multiply(new BigDecimal("0.01")));//分转元
                vo.setBizFreeZenNo(resp.getJSONObject("signedValue").getString("bizFreezenNo"));
                return vo;
            } else {
                throw new BusinessException(Integer.parseInt(resp.getString("errorCode")), resp.getString("message"));
            }
        } else {
            try {
                result = OrderServiceUtil.unfreezeMoney(bizUserId, freezeMoneyReqVO.getBizFreeZenNo(), freezeMoneyReqVO.getAccountSetNo(), freezeMoneyReqVO.getAmount().multiply(new BigDecimal(100)).longValue(), cacheParams, url);//元转分
                resp = JSON.parseObject(result);
            } catch (Exception e) {
                throw new BusinessException(ResponseCode.ALL_IN_PAY_ERROR);
            }
            String status = resp.getString("status");
            if (AllInPayResultEnum.SUCCESS.getMsg().equals(status)) {
                FreezeMoneyRespVO vo = new FreezeMoneyRespVO();
                vo.setAmount(new BigDecimal(resp.getJSONObject("signedValue").getLong("amount")).multiply(new BigDecimal("0.01")));//分转元
                vo.setBizFreeZenNo(resp.getJSONObject("signedValue").getString("bizFreezenNo"));
                return vo;
            } else {
                throw new BusinessException(Integer.parseInt(resp.getString("errorCode")), resp.getString("message"));
            }
        }

    }

    /**
     * 通联支付-查询账户收支明细
     *
     * @param memberId     会员id
     * @param memberRoleId 会员角色id
     * @param dto          查询条件
     * @return 操作结果
     */
    @Override
    public QueryInExpDetailRespVO queryInExpDetail(Long memberId, Long memberRoleId, QueryInExpDetailDTO dto) {
        String bizUserId = memberId + "__" + memberRoleId;//"7407F9AC0A0000270C83A8495419B262";
        String accountSetNo;//需动态获取每个平台的账户集
        String cacheParams = redisStringUtils.get(key, Constants.REDIS_PAY_INDEX);
        JSONObject cacheValue = JSONObject.parseObject(cacheParams);
        if (memberId != 1 && memberRoleId != 1) {
            accountSetNo = cacheValue.getString("44");
        } else {
            accountSetNo = cacheValue.getString("43");
        }
        JSONObject resp;
        try {
            String url = payGateWayConfig.getTestInterfaceUrl();//接口访问地址
            String result = OrderServiceUtil.queryInExpDetail(bizUserId, accountSetNo, dto.getDateStart(), dto.getDateEnd(), dto.getStartPosition(), dto.getQueryNum(), dto.getTradeType(), cacheParams, url);
            resp = JSON.parseObject(result);
        } catch (Exception e) {
            throw new BusinessException(ResponseCode.ALL_IN_PAY_ERROR);
        }
        String status = resp.getString("status");
        if (AllInPayResultEnum.SUCCESS.getMsg().equals(status)) {
            QueryInExpDetailRespVO vo = new QueryInExpDetailRespVO();
            List<InExpDetail> inExpDetails = new ArrayList<>();
            JSONObject signedValue = resp.getJSONObject("signedValue");
            vo.setBizUserId(signedValue.getString("bizUserId"));
            vo.setTotalNum(Long.valueOf(signedValue.getString("totalNum")));
            vo.setExtendInfo(signedValue.getString("extendInfo"));
            JSONArray array = signedValue.getJSONArray("inExpDetail");
            for (int i = 0; i < array.size(); i++) {
                InExpDetail detail = new InExpDetail();
                JSONObject jsonObject = array.getJSONObject(i);
                detail.setTradeNo(jsonObject.getString("tradeNo"));
                detail.setAccountSetName(jsonObject.getString("accountSetName"));
                detail.setChangeTime(jsonObject.getString("changeTime"));
                detail.setCurAmount(new BigDecimal(jsonObject.getLong("curAmount")).multiply(new BigDecimal("0.01")));//分转元
                detail.setOriAmount(new BigDecimal(jsonObject.getLong("oriAmount")).multiply(new BigDecimal("0.01")));
                detail.setChgAmount(new BigDecimal(jsonObject.getLong("chgAmount")).multiply(new BigDecimal("0.01")));
                detail.setCurFreeZenAmount(jsonObject.getLong("curFreeZenAmount"));
                detail.setBizOrderNo(jsonObject.getString("bizOrderNo"));
                detail.setTradeType(jsonObject.getString("tradeType"));
                detail.setType(jsonObject.getString("type"));
                detail.setRemark(jsonObject.getString("remark"));
                detail.setExtendInfo(jsonObject.getString("extendInfo"));
                inExpDetails.add(detail);
            }
            vo.setInExpDetails(inExpDetails);
            return vo;
        } else {
            if (Integer.parseInt(resp.getString("errorCode")) == 30019) {//标识账户还没有交易记录，提示账户不存在
                return new QueryInExpDetailRespVO();
            }
            throw new BusinessException(Integer.parseInt(resp.getString("errorCode")), resp.getString("message"));
        }

    }

    /**
     * 通联支付-查询余额
     *
     * @param memberId     会员id
     * @param memberRoleId 会员角色id
     * @return 操作结果
     */
    @Override
    public BalanceVO queryBalance(Long memberId, Long memberRoleId) {

        String bizUserId = memberId + "__" + memberRoleId;//"7407F9AC0A0000270C83A8495419B262";
        String accountSetNo;//需动态获取每个平台的账户集
        String cacheParams = redisStringUtils.get(key, Constants.REDIS_PAY_INDEX);
        JSONObject cacheValue = JSONObject.parseObject(cacheParams);
        if (memberId != 1 && memberRoleId != 1) {
            accountSetNo = cacheValue.getString("44");
        } else {
            accountSetNo = cacheValue.getString("43");
        }
        JSONObject resp;
        try {
            String url = payGateWayConfig.getTestInterfaceUrl();//接口访问地址
            String result = OrderServiceUtil.queryBalance(bizUserId, accountSetNo, cacheParams, url);
            resp = JSON.parseObject(result);
        } catch (Exception e) {
            throw new BusinessException(ResponseCode.ALL_IN_PAY_ERROR);
        }
        String status = resp.getString("status");
        if (AllInPayResultEnum.SUCCESS.getMsg().equals(status)) {
            BalanceVO vo = new BalanceVO();
            vo.setAllAmount(!((resp.getJSONObject("signedValue").getLong("allAmount")) <= 0) ? new BigDecimal(((resp.getJSONObject("signedValue").getLong("allAmount")))).multiply(new BigDecimal("0.01")) : new BigDecimal("0"));//分转元
            vo.setFreeZenAmount(!((resp.getJSONObject("signedValue").getLong("freezenAmount")) <= 0) ? new BigDecimal((resp.getJSONObject("signedValue").getLong("freezenAmount"))).multiply(new BigDecimal("0.01")) : new BigDecimal("0"));//分转元
            vo.setAvailableAmount(!((((resp.getJSONObject("signedValue").getLong("allAmount")) - resp.getJSONObject("signedValue").getLong("freezenAmount"))) <= 0) ? new BigDecimal(((resp.getJSONObject("signedValue").getLong("allAmount")) - (resp.getJSONObject("signedValue").getLong("freezenAmount")))).multiply(new BigDecimal("0.01")) : new BigDecimal("0"));
            return vo;
        } else {
            throw new BusinessException(Integer.parseInt(resp.getString("errorCode")), resp.getString("message"));
        }

    }

    /**
     * 通联支付-会员绑定支付账户用户标识
     *
     * @param sysUser 当前登录用户
     * @param vo      请求对象
     * @return 绑定结果
     */
    @Override
    public Wrapper<Void> applyBindAcct(UserLoginCacheDTO sysUser, ApplyBindAcctVO vo) {
        String cacheParams = redisStringUtils.get(key, Constants.REDIS_PAY_INDEX);
        String bizUserId = sysUser.getMemberId() + "__" + sysUser.getMemberRoleId();
        try {
            String url = payGateWayConfig.getTestInterfaceUrl();//接口访问地址
            String result = MemberServiceUtil.applyBindAcct(bizUserId, vo.getOperationType(), vo.getAcctType(), vo.getAcct(), cacheParams, url);
            JSONObject resp = JSON.parseObject(result);
            String status = resp.getString("status");
            if (AllInPayResultEnum.SUCCESS.getMsg().equals(status)) {
                return Wrapper.success();
            } else {
                return Wrapper.fail(Integer.parseInt(resp.getString("errorCode")), resp.getString("message"));
            }
        } catch (Exception e) {
            return Wrapper.fail(ResponseCode.ALL_IN_PAY_ERROR);
        }
    }

    /**
     * 通联支付-影印件采集
     *
     * @param sysUser         当前登录用户
     * @param idCardCollectVO 请求数据
     * @return 操作结果
     */
    @Override
    public Wrapper<Object> idCardCollect(UserLoginCacheDTO sysUser, IdCardCollectVO idCardCollectVO) {
        String cacheParams = redisStringUtils.get(key, Constants.REDIS_PAY_INDEX);
        String bizUserId = sysUser.getMemberId() + "__" + sysUser.getMemberRoleId();
        String ocrComparisonResultBackUrl = payGateWayConfig.getNotifyUrl() + YunClient.backUrl + "/idCardCollect";
        //影印件核对结果异步通知地址，不上送则无异步通知
        try {
            String url = payGateWayConfig.getTestInterfaceUrl();//接口访问地址
            String result = MemberServiceUtil.idCardCollect(bizUserId, idCardCollectVO.getPicType(), idCardCollectVO.getPicture(), ocrComparisonResultBackUrl, cacheParams, url);
            JSONObject resp = JSON.parseObject(result);
            String status = resp.getString("status");
            if (AllInPayResultEnum.SUCCESS.getMsg().equals(status)) {
                //修改数据库状态
                AllInPayAttach payAttach = allInPayAttachRepository.findByBizUserId(bizUserId);
                payAttach = payAttach != null ? payAttach : new AllInPayAttach();
                payAttach.setBizUserId(bizUserId);
                String picUrl = payAttach.getPicUrl();
                if (StringUtils.hasLength(picUrl) && !"null".equals(picUrl)) {
                    List<IdCardCollectVO> idCardCollectVOS = JSON.parseArray(picUrl, IdCardCollectVO.class);
                    //如果类型相同则替换
                    if (idCardCollectVOS.stream().map(IdCardCollectVO::getPicType).collect(Collectors.toList()).contains(idCardCollectVO.getPicType())) {
                        for (IdCardCollectVO cardCollectVO : idCardCollectVOS) {
                            if (idCardCollectVO.getPicType().equals(cardCollectVO.getPicType())) {
                                cardCollectVO.setPicture(idCardCollectVO.getPicture());
                            }
                        }
                    } else {
                        //没有相同则直接添加
                        idCardCollectVOS.add(idCardCollectVO);
                    }
                    payAttach.setPicUrl(JSON.toJSONString(idCardCollectVOS));
                    //当图片数量为3时,添加影印件成功
                    if (idCardCollectVOS.size() == 3) {
                        payAttach.setStep(2);
                    }
                } else {
                    List<IdCardCollectVO> idCardCollectVOS = new ArrayList<>();
                    idCardCollectVOS.add(idCardCollectVO);
                    payAttach.setPicUrl(JSON.toJSONString(idCardCollectVOS));
                }
                allInPayAttachRepository.saveAndFlush(payAttach);
                return Wrapper.success();
            } else {
                return Wrapper.fail(Integer.parseInt(resp.getString("errorCode")), resp.getString("message"));
            }
        } catch (Exception e) {
            return Wrapper.fail(ResponseCode.ALL_IN_PAY_ERROR);
        }
    }

    /**
     * 支付能力-支付方式管理-e账户认证-企业账户认证-提交企业信息-进一步提交信息
     *
     * @param sysUser 当前登录用户
     * @param vo      请求参数
     * @return 操作结果
     */
    @Override
    public Wrapper<Void> submitEnterPriseMember(UserLoginCacheDTO sysUser, AllInPaySubmitEnterPriseMemberReqVO vo) {
        String bizUserId = sysUser.getMemberId() + "__" + sysUser.getMemberRoleId();
        AllInPay allInPay = allInPayRepository.findByBizUserId(bizUserId);
        allInPay = allInPay != null ? allInPay : new AllInPay();
        allInPay.setPhone(vo.getPhone());
        allInPay.setContractNo(vo.getContractNo());
        allInPayRepository.saveAndFlush(allInPay);
        return Wrapper.success();
    }

    /**
     * 支付能力-支付方式管理-e账户认证-企业账户认证-提交企业信息
     *
     * @param sysUser 当前登录用户
     * @param vo      请求参数
     * @return 操作结果
     */
    @Override
    public Wrapper<Void> addEnterPriseMember(UserLoginCacheDTO sysUser, AllInPayEnterPriseMemberReqVO vo) {
        String bizUserId = sysUser.getMemberId() + "__" + sysUser.getMemberRoleId();
        //1-先保存数据到通联支付用户信息主表
        AllInPay allInPay = allInPayRepository.findByBizUserId(bizUserId);
        allInPay = allInPay != null ? allInPay : new AllInPay();
        allInPay.setMemberId(sysUser.getMemberId());
        allInPay.setMemberRoleId(sysUser.getMemberRoleId());
        allInPay.setMemberType(Stream.of(MemberTypeEnum.MERCHANT_PERSONAL.getCode(), MemberTypeEnum.CHANNEL_PERSONAL.getCode()).collect(Collectors.toList()).contains(sysUser.getMemberType()) ? 3 : 2);
        allInPay.setBizUserId(bizUserId);
        allInPay.setSysId(YunClient.sysid);
        allInPay.setName(vo.getName());
        allInPay.setCardType(vo.getCardType());
        allInPay.setCardNo(vo.getCardNo());
        allInPay.setPhone(vo.getPhone());
        allInPay.setIsSubmit(1);//标识用户已经提交信息
        allInPayRepository.saveAndFlush(allInPay);
        //2-保存数据到通联支付用户信息附属表
        AllInPayAttach payAttach = allInPayAttachRepository.findByBizUserId(bizUserId);
        payAttach = payAttach != null ? payAttach : new AllInPayAttach();
        payAttach.setBizUserId(bizUserId);
        payAttach.setAccountNo(vo.getAccountNo());
        payAttach.setBankName(vo.getBankName());
        payAttach.setBankNo(vo.getBankNo());
        payAttach.setBranchName(vo.getBranchName());
        payAttach.setPicUrl(JSON.toJSONString(vo.getPicUrl()));
        payAttach.setAllInPay(allInPay);
        payAttach.setCompanyName(vo.getCompanyName());
        payAttach.setStep(1);//已经设置企业信息
        allInPayAttachRepository.saveAndFlush(payAttach);
        return Wrapper.success();
    }

    /**
     * 支付能力-支付方式管理-e账户认证-获取个人/企业用户信息
     *
     * @param sysUser 当前登录用户
     * @return 用户信息
     */
    @Override
    public AllInPayMemberRespVO getAuthMemberInfo(UserLoginCacheDTO sysUser) {
        AllInPayMemberRespVO vo = new AllInPayMemberRespVO();
        String bizUserId = sysUser.getMemberId() + "__" + sysUser.getMemberRoleId();//"626__92";
        //从数据库中获取数据
        //2-从数据库中获取数据
        AllInPay allInPay = allInPayRepository.findByBizUserId(bizUserId);
        if (allInPay != null) {
            BeanUtils.copyProperties(allInPay, vo);
        }
        AllInPayAttach payAttach = allInPayAttachRepository.findByBizUserId(bizUserId);
        if (payAttach != null) {
            vo.setBankNo(payAttach.getBankNo());
            vo.setBankName(payAttach.getBankName());
            vo.setBranchName(payAttach.getBranchName());
            vo.setIsSetPayPwd(payAttach.getIsSetPayPwd());
        }
        if (allInPay != null && Objects.equals(AllInPayMemberTypeEnum.ENTERPRISE.getCode().intValue(), allInPay.getAccountStatus())) {
            if (payAttach != null) {
                vo.setCompanyName(payAttach.getCompanyName());
                vo.setBranchName(payAttach.getBranchName());
                vo.setUniCredit(payAttach.getUniCredit());
                vo.setAccountNo(payAttach.getAccountNo());
                if (StringUtils.hasLength(payAttach.getPicUrl())) {
                    vo.setPicUrl(JSON.parseArray(payAttach.getPicUrl(), IdCardCollectVO.class));
                }
                vo.setOcrRegNumComparisonResult(payAttach.getOcrRegNumComparisonResult());
                vo.setOcrIdCardComparisonResult(payAttach.getOcrIdCardComparisonResult());
                vo.setStep(payAttach.getStep());
            }
        }
        return vo;
    }

    /**
     * 通联支付-获取会员信息
     *
     * @param sysUser 当前登录用户
     * @return 操作结果
     */
    @Transactional(rollbackFor = BusinessException.class)
    @Override
    public AllInPayMemberRespVO getMemberInfo(UserLoginCacheDTO sysUser) {
        String bizUserId = sysUser.getMemberId() + "__" + sysUser.getMemberRoleId();
        AllInPayMemberRespVO vo = new AllInPayMemberRespVO();
        try {
            String cacheParams = redisStringUtils.get(key, Constants.REDIS_PAY_INDEX);
            String url = payGateWayConfig.getTestInterfaceUrl();//接口访问地址
            String result = MemberServiceUtil.getMemberInfo(bizUserId, cacheParams, url);
            JSONObject resp = JSON.parseObject(result);
            String status = resp.getString("status");
            if (AllInPayResultEnum.SUCCESS.getMsg().equals(status)) {
                //1-先保存数据
                JSONObject signedValue = resp.getJSONObject("signedValue");
                Long memberType = signedValue.getLong("memberType");
                JSONObject memberInfo = signedValue.getJSONObject("memberInfo");
                if (Objects.equals(memberType, AllInPayMemberTypeEnum.ENTERPRISE.getCode())) {//企业会员
                    AllInPay allInPay = allInPayRepository.findByBizUserId(bizUserId);
                    allInPay = allInPay != null ? allInPay : new AllInPay();
                    allInPay.setBizUserId(bizUserId);
                    allInPay.setAccountStatus(memberInfo.getInteger("status"));
                    allInPay.setIsSign(memberInfo.getBoolean("isSignContract") ? 1 : 0);
                    allInPay.setContractNo(memberInfo.getString("ContractNo"));
                    allInPay.setIsPhoneChecked(memberInfo.getBoolean("isPhoneChecked") ? 1 : 2);

                    allInPayRepository.saveAndFlush(allInPay);
                    AllInPayAttach payAttach = allInPayAttachRepository.findByBizUserId(bizUserId);
                    payAttach = payAttach != null ? payAttach : new AllInPayAttach();
                    payAttach.setBizUserId(bizUserId);
                    payAttach.setOcrRegNumComparisonResult(memberInfo.getLong("ocrRegnumComparisonResult") != null ? Math.toIntExact(memberInfo.getLong("ocrRegnumComparisonResult")) : 0);
                    payAttach.setOcrIdCardComparisonResult(memberInfo.getLong("ocrIdcardComparisonResult") != null ? Math.toIntExact(memberInfo.getLong("ocrIdcardComparisonResult")) : 0);
                    if (allInPay.getAccountStatus() != null && AllInPayEnterpriseStateEnum.SUCCESSFUL_REVIEW.getCode().equals(allInPay.getAccountStatus()) && payAttach.getStep() < 1) {
                        payAttach.setStep(1);
                    }
                    allInPayAttachRepository.saveAndFlush(payAttach);
                } else {    //个人会员
                    AllInPay allInPay = allInPayRepository.findByBizUserId(bizUserId);
                    allInPay = allInPay != null ? allInPay : new AllInPay();
                    allInPay.setBizUserId(bizUserId);
                    allInPay.setAccountStatus(memberInfo.getInteger("userState"));
                    allInPay.setIsAuth(memberInfo.getBoolean("isIdentityChecked") ? 1 : 0);
                    allInPay.setIsSign(memberInfo.getBoolean("isSignContract") ? 1 : 0);
                    allInPay.setContractNo(memberInfo.getString("contractNo"));
                    allInPayRepository.saveAndFlush(allInPay);
                }
                //2-从数据库中获取数据
                AllInPay allInPay = allInPayRepository.findByBizUserId(bizUserId);
                BeanUtils.copyProperties(allInPay, vo);
                AllInPayAttach payAttach = allInPayAttachRepository.findByBizUserId(bizUserId);
                if (payAttach != null) {
                    vo.setBankNo(payAttach.getBankNo());
                    vo.setBankName(payAttach.getBankName());
                    vo.setBranchName(payAttach.getBranchName());
                    vo.setIsSetPayPwd(payAttach.getIsSetPayPwd());
                }
                if (Objects.equals(AllInPayMemberTypeEnum.ENTERPRISE.getCode().intValue(), allInPay.getAccountStatus())) {
                    if (payAttach != null) {
                        vo.setCompanyName(payAttach.getCompanyName());
                        vo.setBranchName(payAttach.getBranchName());
                        vo.setUniCredit(payAttach.getUniCredit());
                        vo.setAccountNo(payAttach.getAccountNo());
                        if (StringUtils.hasLength(payAttach.getPicUrl())) {
                            vo.setPicUrl(JSON.parseArray(payAttach.getPicUrl(), IdCardCollectVO.class));
                        }
                        vo.setOcrRegNumComparisonResult(payAttach.getOcrRegNumComparisonResult());
                        vo.setOcrIdCardComparisonResult(payAttach.getOcrIdCardComparisonResult());
                        vo.setStep(payAttach.getStep());
                    }
                }
                return vo;
            } else {
                return getAuthMemberInfo(sysUser);
            }
        } catch (Exception e) {
            throw new BusinessException(ResponseCode.ALL_IN_PAY_ERROR);
        }
    }

    /**
     * 通联支付-企业会员绑定对公户
     *
     * @param sysUser 当前登录用户
     * @param vo      请求参数
     * @return 操作结果
     */
    @Override
    public Wrapper<Void> bindCompanyAccount(UserLoginCacheDTO sysUser, BindCompanyAccountVO vo) {
        String bizUserId = sysUser.getMemberId() + "__" + sysUser.getMemberRoleId();
        try {
            //保存对公账号信息
            AllInPayAttach allInPayAttach = allInPayAttachRepository.findByBizUserIdAndAccountNo(bizUserId, vo.getAccountNo());
            if (!Objects.isNull(allInPayAttach)) {
                allInPayAttach.setStep(4);//绑定对公账号
                allInPayAttachRepository.saveAndFlush(allInPayAttach);
                return Wrapper.success();
            } else {
                return Wrapper.fail(ResponseCode.ALL_IN_PAY_ERROR);
            }

        } catch (Exception e) {
            return Wrapper.fail(ResponseCode.ALL_IN_PAY_ERROR);
        }
    }

    /**
     * 通联支付-设置企业信息
     *
     * @param sysUser 当前登录用户
     * @param vo      请求参数
     * @return 操作结果
     */
    @Transactional(rollbackFor = BusinessException.class)
    @Override
    public Wrapper<Void> setCompanyInfo(UserLoginCacheDTO sysUser, AllInPayEnterPriseMemberReqVO vo) {
        String cacheParams = redisStringUtils.get(key, Constants.REDIS_PAY_INDEX);
        String bizUserId = sysUser.getMemberId() + "__" + sysUser.getMemberRoleId();
        try {
            Map<Object, Object> map = new HashMap<>();
            //封装企业基本信息
            map.put("companyName", vo.getCompanyName());
            map.put("legalName", vo.getName());
            map.put("identityType", vo.getCardType());
            map.put("legalIds", RSAUtil.encrypt(vo.getCardNo()));
            map.put("legalPhone", vo.getPhone());
            map.put("accountNo", RSAUtil.encrypt(vo.getAccountNo()));
            map.put("parentBankName", vo.getBankName());
            map.put("bankName", vo.getBranchName());
            map.put("unionBank", vo.getBankNo());
            map.put("authType", 2);
            map.put("uniCredit", vo.getUniCredit());
            JSONObject companyBasicInfo = JSON.parseObject(YunClient.jsonToStr(map));
            String url = payGateWayConfig.getTestInterfaceUrl();//接口访问地址
            String result = MemberServiceUtil.setCompanyInfo(bizUserId, companyBasicInfo, vo.getIsAuth(), cacheParams, url);//true：系统自动审核 false：需人工审核
            JSONObject resp = JSON.parseObject(result);
            String status = resp.getString("status");
            if (AllInPayResultEnum.SUCCESS.getMsg().equals(status)) {
                JSONObject signedValue = resp.getJSONObject("signedValue");
                //保存企业信息
                AllInPay allInPay = allInPayRepository.findByBizUserId(bizUserId);
                allInPay = allInPay != null ? allInPay : new AllInPay();
                allInPay.setMemberId(sysUser.getMemberId());
                allInPay.setMemberRoleId(sysUser.getMemberRoleId());
                allInPay.setMemberType(Stream.of(MemberTypeEnum.MERCHANT_PERSONAL.getCode(), MemberTypeEnum.CHANNEL_PERSONAL.getCode()).collect(Collectors.toList()).contains(sysUser.getMemberType()) ? 3 : 2);
                allInPay.setBizUserId(bizUserId);
                allInPay.setSysId(YunClient.sysid);
                allInPay.setName(vo.getName());
                allInPay.setCardType(vo.getCardType());
                allInPay.setCardNo(vo.getCardNo());
                allInPay.setPhone(vo.getPhone());
                allInPay.setIsSubmit(1);//标识用户已经提交信息
                AllInPayAttach payAttach = allInPayAttachRepository.findByBizUserId(bizUserId);
                payAttach = payAttach != null ? payAttach : new AllInPayAttach();
                payAttach.setBizUserId(bizUserId);
                payAttach.setAccountNo(vo.getAccountNo());
                payAttach.setBankName(vo.getBankName());
                payAttach.setBankNo(vo.getBankNo());
                payAttach.setBranchName(vo.getBranchName());
                payAttach.setUniCredit(vo.getUniCredit());
                payAttach.setPicUrl(JSON.toJSONString(vo.getPicUrl()));
                payAttach.setAllInPay(allInPay);
                payAttach.setCompanyName(vo.getCompanyName());
                if (signedValue.getLong("result") != null && signedValue.getLong("result") == 2) {
                    payAttach.setStep(1);//已经设置企业信息
                }
                allInPayAttachRepository.saveAndFlush(payAttach);
                return Wrapper.success();
            } else {
                return Wrapper.fail(Integer.parseInt(resp.getString("errorCode")), resp.getString("message"));
            }
        } catch (Exception e) {
            return Wrapper.fail(ResponseCode.ALL_IN_PAY_ERROR);
        }
    }

    /**
     * 支付能力-支付方式管理-e账户认证-个人账户认证-修改个人信息
     *
     * @param sysUser                     当前登录用户
     * @param allInPayUpdatePersonalReqVO 请求参数
     * @return 操作结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Wrapper<Void> updatePersonal(UserLoginCacheDTO sysUser, AllInPayUpdatePersonalReqVO allInPayUpdatePersonalReqVO) {
        String bizUserId = sysUser.getMemberId() + "__" + sysUser.getMemberRoleId();
        AllInPay allInPay = allInPayRepository.findByBizUserId(bizUserId);
        BeanUtils.copyProperties(allInPayUpdatePersonalReqVO, allInPay);
        allInPayRepository.saveAndFlush(allInPay);
        AllInPayAttach allInPayAttach = allInPayAttachRepository.findByBizUserId(bizUserId);
        BeanUtils.copyProperties(allInPayUpdatePersonalReqVO, allInPayAttach);
        allInPayAttachRepository.saveAndFlush(allInPayAttach);
        return Wrapper.success();
    }

    /**
     * 通联支付-解绑绑定银行卡
     *
     * @param sysUser       当前操作用户
     * @param unBindPhoneVO 银行卡号
     * @return 操作结果
     */
    @Override
    public Wrapper<Void> unbindBankCard(UserLoginCacheDTO sysUser, UnBindPhoneVO unBindPhoneVO) {
        String cacheParams = redisStringUtils.get(key, Constants.REDIS_PAY_INDEX);
        String bizUserId = sysUser.getMemberId() + "__" + sysUser.getMemberRoleId();
        try {
            String url = payGateWayConfig.getTestInterfaceUrl();//接口访问地址
            String result = MemberServiceUtil.unbindBankCard(bizUserId, unBindPhoneVO.getCardNo(), cacheParams, url);
            JSONObject resp = JSON.parseObject(result);
            String status = resp.getString("status");
            if (AllInPayResultEnum.SUCCESS.getMsg().equals(status)) {
                //删除表中的银行卡信息
                AllInPayAttach allInPayAttach = allInPayAttachRepository.findByBizUserId(bizUserId);
                allInPayAttach.setBankName(null);
                allInPayAttach.setBankNo(null);
                allInPayAttachRepository.saveAndFlush(allInPayAttach);
                return Wrapper.success();
            } else {
                return Wrapper.fail(Integer.parseInt(resp.getString("errorCode")), resp.getString("message"));
            }
        } catch (Exception e) {
            return Wrapper.fail(ResponseCode.ALL_IN_PAY_ERROR);
        }
    }

    /**
     * 通联支付-解绑手机（验证原手机短信验证码）
     *
     * @param sysUser     当前登录用户
     * @param bindPhoneVO 请求参数
     * @return 解绑结果
     */
    @Override
    public Wrapper<Void> unbindPhone(UserLoginCacheDTO sysUser, BindPhoneVO bindPhoneVO) {
        String cacheParams = redisStringUtils.get(key, Constants.REDIS_PAY_INDEX);
        String bizUserId = sysUser.getMemberId() + "__" + sysUser.getMemberRoleId();
        try {
            String url = payGateWayConfig.getTestInterfaceUrl();//接口访问地址
            String result = MemberServiceUtil.unbindPhone(bizUserId, bindPhoneVO.getPhone(), bindPhoneVO.getVerificationCode(), cacheParams, url);
            JSONObject resp = JSON.parseObject(result);
            String status = resp.getString("status");
            if (AllInPayResultEnum.SUCCESS.getMsg().equals(status)) {
                //删除表中的phone记录
                AllInPay allInPay = allInPayRepository.findByBizUserId(bizUserId);
                allInPay.setPhone(null);
                allInPayRepository.saveAndFlush(allInPay);
                return Wrapper.success();
            } else {
                return Wrapper.fail(Integer.parseInt(resp.getString("errorCode")), resp.getString("message"));
            }
        } catch (Exception e) {
            return Wrapper.fail(ResponseCode.ALL_IN_PAY_ERROR);
        }
    }

    /**
     * 支付能力-支付方式管理-e账户认证-个人账户认证-进一步信息提交
     *
     * @param sysUser    当前登录用户
     * @param bankCardVO 请求参数
     * @return 操作结果
     */
    @Override
    public Wrapper<Void> submitPersonal(UserLoginCacheDTO sysUser, BankCardVO bankCardVO) {
        String bizUserId = sysUser.getMemberId() + "__" + sysUser.getMemberRoleId();
        //先判断用户是否已经进行签约
        AllInPay allInPay = allInPayRepository.findByBizUserId(bizUserId);
        if (allInPay.getIsSign() != 1) {
            return Wrapper.fail(AllInPayErrorCodeEnum.THE_MEMBER_HAS_NOT_SIGNED_AN_ELECTRONIC_AGREEMENT.getMsg());
        }
        AllInPayAttach payAttach = allInPayAttachRepository.findByBizUserId(bizUserId);
        payAttach.setBizUserId(bizUserId);
        payAttach.setBankName(bankCardVO.getBankName());
        payAttach.setBankNo(bankCardVO.getBankNo());
        allInPayAttachRepository.saveAndFlush(payAttach);
        return Wrapper.success();
    }

    /**
     * 通联支付会员确认绑定银行卡
     *
     * @param sysUser    当前登录用户
     * @param bankCardVO 请求参数
     * @return 操作结果
     */
    @Override
    public Wrapper<Void> bindBankCard(UserLoginCacheDTO sysUser, BindBankCardVO bankCardVO) {
        String cacheParams = redisStringUtils.get(key, Constants.REDIS_PAY_INDEX);
        String bizUserId = sysUser.getMemberId() + "__" + sysUser.getMemberRoleId();
        try {
            AllInPayAttach payAttach = allInPayAttachRepository.findByBizUserId(bizUserId);
            String tranceNum = null;
            if (payAttach != null) {
                tranceNum = payAttach.getTranceNum();
            }
            String url = payGateWayConfig.getTestInterfaceUrl();//接口访问地址
            String result = MemberServiceUtil.bindBankCard(bizUserId, tranceNum, null, bankCardVO.getPhone(), bankCardVO.getVerificationCode(), cacheParams, url);
            JSONObject resp = JSON.parseObject(result);
            String status = resp.getString("status");
            if (AllInPayResultEnum.SUCCESS.getMsg().equals(status)) {
                JSONObject signedValue = resp.getJSONObject("signedValue");
                //保存数据
                AllInPayAttach allInPayAttach = allInPayAttachRepository.findByBizUserId(bizUserId);
                allInPayAttach = allInPayAttach != null ? allInPayAttach : new AllInPayAttach();
                allInPayAttach.setBizUserId(bizUserId);
                allInPayAttach.setTranceNum(signedValue.getString("tranceNum"));
                allInPayAttach.setAgreementNo(signedValue.getString("agreementNo"));
                allInPayAttach.setBankNo(bankCardVO.getCardNo());
                allInPayAttach.setBankName(bankCardVO.getBankName());
                allInPayAttachRepository.saveAndFlush(allInPayAttach);
                return Wrapper.success();
            } else {
                return Wrapper.fail(Integer.parseInt(resp.getString("errorCode")), resp.getString("message"));
            }
        } catch (Exception e) {
            return Wrapper.fail(ResponseCode.ALL_IN_PAY_ERROR);
        }
    }

    /**
     * 通联支付会员请求绑定银行卡
     *
     * @param sysUser 当前登录用户
     * @param vo      请求参数
     * @return 操作结果
     */
    @Override
    public Wrapper<Object> applyBindBankCard(UserLoginCacheDTO sysUser, ApplyBindBankCardVO vo) {
        String cacheParams = redisStringUtils.get(key, Constants.REDIS_PAY_INDEX);
        String bizUserId = sysUser.getMemberId() + "__" + sysUser.getMemberRoleId();
        try {
            String url = payGateWayConfig.getTestInterfaceUrl();//接口访问地址
            String result = MemberServiceUtil.applyBindBankCard(bizUserId, vo.getCardCheck(), vo.getPhone(), vo.getCardNo(), vo.getName(), vo.getIdentityType(), vo.getIdentityNo(), null, null, null, null, cacheParams, url);
            JSONObject resp = JSON.parseObject(result);
            String status = resp.getString("status");
            if (AllInPayResultEnum.SUCCESS.getMsg().equals(status)) {
                JSONObject signedValue = resp.getJSONObject("signedValue");
                //保存流水号
                AllInPayAttach payAttach = allInPayAttachRepository.findByBizUserId(bizUserId);
                payAttach = payAttach != null ? payAttach : new AllInPayAttach();
                payAttach.setBizUserId(bizUserId);
                payAttach.setTranceNum(signedValue.getString("tranceNum"));
                payAttach.setBankCode(signedValue.getString("bankCode"));
                payAttach.setCardType(signedValue.getLong("cardType").intValue());
                allInPayAttachRepository.saveAndFlush(payAttach);
                return Wrapper.success();
            } else {
                return Wrapper.fail(Integer.parseInt(resp.getString("errorCode")), resp.getString("message"));
            }
        } catch (Exception e) {
            return Wrapper.fail(ResponseCode.ALL_IN_PAY_ERROR);
        }
    }

    /**
     * 通联支付会员电子协议签约查询
     *
     * @param sysUser 当前登录用户
     * @return 操作结果
     */
    @Override
    public Wrapper<String> signContractQuery(UserLoginCacheDTO sysUser, SignContractVO signContractVO) {
        String cacheParams = redisStringUtils.get(key, Constants.REDIS_PAY_INDEX);
        String bizUserId = sysUser.getMemberId() + "__" + sysUser.getMemberRoleId();
        String gateWayUrl = payGateWayConfig.getTestSignContract();//测试
        //   String gateWayUrl = "http://116.228.64.55:6900/yungateway/member/signContract.html";//测试
        //  String gateWayUrl = "https://fintech.allinpay.com/yungateway/member/signContract.html";//正式
        try {
            String result = MemberServiceUtil.signContractQuery(bizUserId, signContractVO.getJumpPageType(), null, gateWayUrl, cacheParams);
            return Wrapper.success(result);

        } catch (Exception e) {
            return Wrapper.fail(ResponseCode.ALL_IN_PAY_ERROR);
        }
    }

    /**
     * 通联支付会员电子协议签约
     *
     * @param sysUser        当前登录用户
     * @param signContractVO 请求对象
     * @return 操作结果
     */
    @Override
    public Wrapper<String> signContract(UserLoginCacheDTO sysUser, SignContractVO signContractVO) {
        String cacheParams = redisStringUtils.get(key, Constants.REDIS_PAY_INDEX);
        String bizUserId = sysUser.getMemberId() + "__" + sysUser.getMemberRoleId();
        String gateWayUrl = payGateWayConfig.getTestSignContract();//测试
        //String gateWayUrl = "http://116.228.64.55:6900/yungateway/member/signContract.html";//测试
        //  String gateWayUrl = "https://fintech.allinpay.com/yungateway/member/signContract.html";//正式
        Integer source = 2;//1-Mobile 2-PC,此属性不影响登录端是app还是pc
        try {
            String backUrl = payGateWayConfig.getNotifyUrl() + YunClient.backUrl + "/signContract";//后台通知回调地址
            String result = MemberServiceUtil.signContract(bizUserId, signContractVO.getJumpPageType(), backUrl, source, gateWayUrl, cacheParams);
            return Wrapper.success(result);
        } catch (Exception e) {
            return Wrapper.fail(ResponseCode.ALL_IN_PAY_ERROR);
        }
    }

    /**
     * 支付能力-支付方式管理-e账户认证-个人账户认证
     *
     * @param sysUser   当前登录用户
     * @param authReqVO 请求数据
     * @return 操作结果
     */
    @Override
    public Wrapper<Void> personalCrate(UserLoginCacheDTO sysUser, AllInPayPersonalAuthReqVO authReqVO) {
        String bizUserId = sysUser.getMemberId() + "__" + sysUser.getMemberRoleId();
        //1-判断手机号码是否绑定成功
        try {
            String url = payGateWayConfig.getTestInterfaceUrl();//接口访问地址
            String cacheParams = redisStringUtils.get(key, Constants.REDIS_PAY_INDEX);
            String result = MemberServiceUtil.bindPhone(bizUserId, authReqVO.getPhone(), authReqVO.getVerificationCode(), cacheParams, url);
            JSONObject resp = JSON.parseObject(result);
            String status = resp.getString("status");
            if (AllInPayResultEnum.SUCCESS.getMsg().equals(status)) {
                //2-如果成功则实名验证
                String realNameResult = MemberServiceUtil.setRealName(bizUserId, authReqVO.getName(), String.valueOf(authReqVO.getCardType()), authReqVO.getCardNo(), cacheParams, url);
                JSONObject realNameResp = JSON.parseObject(realNameResult);
                String realNameStatus = realNameResp.getString("status");
                if (AllInPayResultEnum.SUCCESS.getMsg().equals(realNameStatus)) {
                    //从本地数据库查询当前用户是否创建会员成功
                    AllInPay allInPay = allInPayRepository.findByBizUserId(sysUser.getMemberId() + "__" + sysUser.getMemberRoleId());
                    if (allInPay == null) {
                        return Wrapper.fail(ResponseCode.ALL_IN_PAY_NOT_EXIST_MEMBER_ERROR);
                    }
                    allInPay.setBizUserId(bizUserId);
                    allInPay.setName(authReqVO.getName());
                    allInPay.setCardType(authReqVO.getCardType());
                    allInPay.setCardNo(authReqVO.getCardNo());
                    allInPay.setPhone(authReqVO.getPhone());
                    allInPay.setIsSubmit(1);//标识用户已经提交信息
                    allInPayRepository.saveAndFlush(allInPay);
                    return Wrapper.success();
                } else {
                    return Wrapper.fail(Integer.parseInt(resp.getString("errorCode")), resp.getString("message"));
                }
            } else {
                return Wrapper.fail(Integer.parseInt(resp.getString("errorCode")), resp.getString("message"));
            }
        } catch (Exception e) {
            return Wrapper.fail(ResponseCode.ALL_IN_PAY_ERROR);
        }


    }

    /**
     * 通联支付个人实名验证
     *
     * @param sysUser   当前登录用户
     * @param authReqVO 请求数据
     * @return 操作结果
     */
    @Override
    public Wrapper<Void> setRealName(UserLoginCacheDTO sysUser, AllInPayPersonalAuthReqVO authReqVO) {
        String cacheParams = redisStringUtils.get(key, Constants.REDIS_PAY_INDEX);
        String bizUserId = sysUser.getMemberId() + "__" + sysUser.getMemberRoleId();
        try {
            String url = payGateWayConfig.getTestInterfaceUrl();//接口访问地址
            String result = MemberServiceUtil.setRealName(bizUserId, authReqVO.getName(), String.valueOf(authReqVO.getCardType()), authReqVO.getCardNo(), cacheParams, url);
            JSONObject resp = JSON.parseObject(result);
            String status = resp.getString("status");
            if (AllInPayResultEnum.SUCCESS.getMsg().equals(status)) {
                //实名成功后修改数据库状态
                AllInPay allInPay = allInPayRepository.findByBizUserId(bizUserId);
                allInPay.setIsAuth(1);
                allInPay.setCardNo(authReqVO.getCardNo());
                allInPay.setCardType(authReqVO.getCardType());
                allInPay.setName(authReqVO.getName());
                allInPay.setPhone(authReqVO.getPhone());
                allInPayRepository.saveAndFlush(allInPay);
                return Wrapper.success();
            } else {
                return Wrapper.fail(Integer.parseInt(resp.getString("errorCode")), resp.getString("message"));
            }
        } catch (Exception e) {
            return Wrapper.fail(ResponseCode.ALL_IN_PAY_ERROR);
        }

    }

    /**
     * 调用通联支付绑定手机
     *
     * @param sysUser     当前登录用户
     * @param bindPhoneVO 请求数据
     * @return 操作结果
     */
    @Transactional(rollbackFor = BusinessException.class)
    @Override
    public Wrapper<Void> bindPhone(UserLoginCacheDTO sysUser, BindPhoneVO bindPhoneVO) {
        String cacheParams = redisStringUtils.get(key, Constants.REDIS_PAY_INDEX);
        String bizUserId = sysUser.getMemberId() + "__" + sysUser.getMemberRoleId();
        try {
            String url = payGateWayConfig.getTestInterfaceUrl();//接口访问地址
            String result = MemberServiceUtil.bindPhone(bizUserId, bindPhoneVO.getPhone(), bindPhoneVO.getVerificationCode(), cacheParams, url);
            JSONObject resp = JSON.parseObject(result);
            String status = resp.getString("status");
            if (AllInPayResultEnum.SUCCESS.getMsg().equals(status)) {
                //保存用户手机
                AllInPay allInPay = allInPayRepository.findByBizUserId(bizUserId);
                allInPay.setPhone(bindPhoneVO.getPhone());
                allInPayRepository.saveAndFlush(allInPay);
                //保存步骤
                int memberType = Stream.of(MemberTypeEnum.MERCHANT_PERSONAL.getCode(), MemberTypeEnum.CHANNEL_PERSONAL.getCode()).collect(Collectors.toList()).contains(sysUser.getMemberType()) ? 3 : 2;
                if (memberType == 2) {
                    AllInPayAttach payAttach = allInPayAttachRepository.findByBizUserId(bizUserId);
                    //存在用户解绑手机再次绑定手机情况
                    payAttach.setStep(payAttach.getStep() > 3 ? 4 : 3);//绑定手机号
                    allInPayAttachRepository.saveAndFlush(payAttach);
                }
                return Wrapper.success();
            } else {
                return Wrapper.fail(Integer.parseInt(resp.getString("errorCode")), resp.getString("message"));
            }
        } catch (Exception e) {
            return Wrapper.fail(ResponseCode.ALL_IN_PAY_ERROR);
        }
    }

    /**
     * 调用通联支付发送短信验证码
     *
     * @param sysUser                当前登录用户
     * @param sendVerificationCodeVO 请求数据
     * @return 操作结果
     */
    @Override
    public Wrapper<Void> sendVerificationCode(UserLoginCacheDTO sysUser, SendVerificationCodeVO sendVerificationCodeVO) {
        String cacheParams = redisStringUtils.get(key, Constants.REDIS_PAY_INDEX);
        String bizUserId = sysUser.getMemberId() + "__" + sysUser.getMemberRoleId();
        try {
            String url = payGateWayConfig.getTestInterfaceUrl();//接口访问地址
            String result = MemberServiceUtil.sendVerificationCode(bizUserId, sendVerificationCodeVO.getPhone(), sendVerificationCodeVO.getVerificationCodeType(), cacheParams, url);
            JSONObject resp = JSON.parseObject(result);
            String status = resp.getString("status");
            if (AllInPayResultEnum.SUCCESS.getMsg().equals(status)) {
                return Wrapper.success();
            } else {
                return Wrapper.fail(Integer.parseInt(resp.getString("errorCode")), resp.getString("message"));
            }
        } catch (Exception e) {
            return Wrapper.fail(ResponseCode.ALL_IN_PAY_ERROR);
        }
    }

    /**
     * 调用通联支付创建会员
     *
     * @param user 当前登录会员
     * @return 操作结果
     */
    @Override
    public Wrapper<Void> createMember(UserLoginCacheDTO user) {
        String cacheParams = redisStringUtils.get(key, Constants.REDIS_PAY_INDEX);
        String bizUserId = user.getMemberId() + "__" + user.getMemberRoleId();
        //3-个人会员 2-企业会员
        Integer allInMemberType = Stream.of(MemberTypeEnum.MERCHANT_PERSONAL.getCode(), MemberTypeEnum.CHANNEL_PERSONAL.getCode()).collect(Collectors.toList()).contains(user.getMemberType()) ? 3 : 2;
        try {
            String url = payGateWayConfig.getTestInterfaceUrl();//接口访问地址
            String result = MemberServiceUtil.createMember(bizUserId, allInMemberType, 2, cacheParams, url);  //source:1-Mobile 2-PC (不影响端登录)
            JSONObject resp = JSON.parseObject(result);
            String status = resp.getString("status");
            if (AllInPayResultEnum.SUCCESS.getMsg().equals(status)) {
                //保存数据
                JSONObject signedValue = resp.getJSONObject("signedValue");
                AllInPay pay = new AllInPay();
                pay.setMemberId(user.getMemberId());
                pay.setMemberName(user.getUserName());
                pay.setMemberRoleId(user.getMemberRoleId());
                pay.setMemberRoleName(user.getMemberRoleName());
                pay.setMemberType(user.getMemberType());
                pay.setAllInMemberType(allInMemberType);
                pay.setBizUserId(bizUserId);
                pay.setSysId(YunClient.sysid);
                pay.setUserId(String.valueOf(signedValue.getString("userId")));
                pay.setMemberLevelType(user.getMemberLevelType());
                allInPayRepository.saveAndFlush(pay);
                return Wrapper.success();
            } else if (AllInPayErrorCodeEnum.USER_ALREADY_EXISTS.getCode().equals(Integer.parseInt(resp.getString("errorCode")))) {
                return Wrapper.success();
            } else {
                return Wrapper.fail(Integer.parseInt(resp.getString("errorCode")), resp.getString("message"));
            }
        } catch (Exception e) {
            return Wrapper.fail(ResponseCode.ALL_IN_PAY_ERROR);
        }
    }


}
